class Tweet < ActiveResource::Base
  # umm:
  # ActiveResource::Base.logger = RAILS_DEFAULT_LOGGER
  self.site = "http://twitter.com"
  self.user = "crsrapid"
  self.password = "crs123"
  # self.user = "mapthegame"
  # self.password = "poopies"
  
  # validates_uniqueness_of :
  
  # Get the latest 20 public statuses
  # Optionally take in :since_id and get updates since passed id
  # Can't figure out how to get a :from and a :params
  def self.public_timeline(params={})
    find(:all, :from=>:public_timeline)
  end

  # Get 20 most recent statuses from authenticated user and his/her friends in the last 24 hours
  # Optionally take in :since timestamp in format: Tue%2C+27+Mar+2007+22%3A55%3A48+GMT
  # Can't figure out how to get a :from and a :params
  def self.friends_timeline(params={})
    find(:all, :from=>:friends_timeline)
  end

  # Get friends timeline for a specified user
  # Can be user id or username
  # Need to implement the :since param as in friends_timeline
  def self.user_and_friends_timeline(id)
    find(:all, :from=>"/statuses/friends_timeline/#{id.to_s}.xml")
  end

  # Get timeline for a user
  # Need to implement :count (limit 20) and :since timestamp
  def self.user_timeline(id)
    find(:all, :from=>"/statuses/user_timeline/#{id.to_s}.xml")
  end

  # Get a specific status
  # Not really RESTful because the 'show' part is extraneous
  def self.show(id)
    find(:one, :from=>"/statuses/show/#{id.to_s}.xml")
  end
  
  def self.update_status(content)
    connection.post("/statuses/update.xml?status="+CGI.escape(content))
  end

  def self.send_to_user(username,content)
    connection.post("/statuses/update.xml?status="+CGI.escape("@"+username+" "+content))
    
  end
  
  def words
    self.text.strip.split(" ")
  end
  
  def timestamp
    Time.parse(self.created_at)
  end
  
  def geocode
    geo = GeoKit::Geocoders::MultiGeocoder.geocode(self.text)
    errors.add(:address, "Could not Geocode address") if !geo.success
    # self.lat, self.lng = geo.lat,geo.lng if geo.success
    if geo.success
      [geo.lat,geo.lng]
    else
      [0,0]
    end
  end
  
  def is_location?
    self.text[0,2].downcase == "l:"
  end

  def is_move?
    self.text[0,4].downcase == "move"
  end
  
  def is_mapthegame?
    (self.text.strip.downcase[0,4] == "yale" || self.text.strip.downcase[0,7] == "harvard") && !self.is_nextmap?
  end
  
  def is_nextmap?
    self.text.downcase[0,7] == "form-id"
  end
  
  def is_message_part?
    self.text.downcase[0,2] == "f="
  end
  
  def cleantext
    if self.is_mapthegame?
      if self.text.strip.downcase[0,4] == "yale"
        self.text[4,self.text.length]+" Massachusetts"
      elsif self.text.strip.downcase[0,7] == "harvard"
        self.text[7,self.text.length]+" Massachusetts"
      end     
    else
      self.text
    end
  end
  
  def save_as_ping
    # converts to pings, also sorts 'message', 'locate', 'move', 'home'
    ping = Ping.new
    ping.content = self.text
    
    if self.is_location?
      geo = GeoKit::GeoLoc.geocode(self.cleantext)
      # self.lat, self.lng = geo.lat,geo.lng if geo.success
      if geo.success
        ping.address = geo.full_address
        ping.country = geo.country_code
        ping.state = geo.state
        ping.locality = geo.city
        ping.street_number = geo.street_number unless geo.street_number.nil?
        ping.thoroughfare = geo.street_name
        ping.postalcode = geo.zip
        ping.accuracy = geo.precision

        ping.latitude = geo.lat
        ping.longitude = geo.lng
        ping.ping_type = 0
      
        ping.twitter_username = self.user.screen_name
        ping.created_at = Time.parse(self.created_at)
        ping.save!

        # self.imported = 1
        # self.save!
      else
        errors.add(:address, "Could not Geocode address")
      end
    elsif self.is_move?
      prev = Ping.find :last, :conditions => {:twitter_username => self.user.screen_name,:ping_type => 0}
      unless prev.nil?
        ping = prev.clone
        if self.is_nextmap?
          ping.ping_type = 3
        else
          ping.ping_type = 1
        end
        ping.content = self.text
        ping.message = self.text
        ping.created_at = Time.parse(self.created_at)

        # parse direction and distance
        # self.text
        # ping.
        
        ping.save!
      end
    elsif self.is_home?
    else #uncategorizable, just a message
      prev = Ping.find :last, :conditions => {:twitter_username => self.user.screen_name,:ping_type => 0}
      unless prev.nil?
        ping = prev.clone
        if self.is_nextmap?
          ping.ping_type = 3
        else
          ping.ping_type = 1
        end
        ping.content = self.text
        ping.message = self.text
        ping.created_at = Time.parse(self.created_at)
        ping.save!
      end
    end
    if !geo.nil? && geo.success
      ping
    else
      false
    end
  end
  
  def part_meta_fields
    payload_split = self.text.split("$")
    payload_split[0].split("&")
  end
  
  def part_payload
    payload_split = self.text.split("$")
    payload_split[1]
  end
  
  def part_meta_fields_hash
    fields = {}
    for message in self.part_meta_fields
      pair = message.split("=")
      fields[pair[0]] = pair[1]
    end
    fields 
  end
  
  def save_as_message_part
    # Saves this tweet as a message part in the local table assuming that is_message_part? is true
    part = MessageParts.new
    if self.is_message_part?
      # Meta Data in the form "f=<form_id>&p=<current_part>,<total_parts>$<payload>"
      part.form_id = part_meta_fields_hash['f']
      part_split = part_meta_fields_hash['p'].split(",")
      part.current_part = part_split[0]
      part.total_parts = part_split[1]
      part.payload = self.part_payload
      part.twitter_username = self.user.screen_name
    end
    part.created_at = Time.parse(self.created_at)
    part.processed = false
    part.save!
  end
           
    
end
